package cn.maka.service;

import cn.maka.dao.UserDAO;
import cn.maka.dao.impl.UserDaoImpl;
import cn.maka.domain.PageBean;
import cn.maka.domain.User;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    UserDAO userDao = new UserDaoImpl();
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User login(User loginUser) {
        return userDao.findUserByUsernameAndPassword(loginUser.getUsername(),loginUser.getPassword());
    }

    @Override
    public User findUserById(String id) {
        return userDao.findUserById(Integer.parseInt(id));
    }

    @Override
    public void addUser(User user) {
        userDao.add(user);
    }

    @Override
    public void delUser(String id) {
        userDao.del(Integer.parseInt(id));
    }

    @Override
    public void updateUser(User user) {
        userDao.update(user);
    }

    @Override
    public void delSelectedUsers(String[] delIds) {
        /*for(int i=0; i<delIds.length; i++){
            userDao.del(Integer.parseInt(delIds[i]));
        }*/

        for (String delId : delIds) {
            userDao.del(Integer.parseInt(delId));
        }
    }

    @Override
    public PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition) {
        PageBean<User> userPageBean = new PageBean<>();

        int intCurrentPage = Integer.parseInt(currentPage);
        int intRows = Integer.parseInt(rows);

        int totalCount =  userDao.findTotalCount(condition);
        int totalPage = (int) Math.ceil( ((float)totalCount) / intRows);

        int start = (intCurrentPage - 1) * intRows;
        List<User> userList = userDao.findByPage(start,intRows,condition);

        userPageBean.setCurrentPage(intCurrentPage);
        userPageBean.setRows(intRows);
        userPageBean.setTotalCount(totalCount);
        userPageBean.setTotalPage(totalPage);
        userPageBean.setList(userList);

        return userPageBean;
    }
}
